package com.starsea.book.ui.newpage.utils

import android.graphics.Rect
import android.os.Build
import android.view.View
import android.view.ViewGroup

object ViewGroupUtils {
  private var IMPL: ViewGroupUtilsImpl? = null

  init {
    val version = Build.VERSION.SDK_INT
    if (version >= 11) {
      IMPL = ViewGroupUtilsImplHoneycomb()
    } else {
      IMPL = ViewGroupUtilsImplBase()
    }
  }

  /**
   * This is a port of the common
   * [ViewGroup.offsetDescendantRectToMyCoords]
   * from the framework, but adapted to take transformations into account. The result
   * will be the bounding rect of the real transformed rect.
   *
   * @param descendant view defining the original coordinate system of rect
   * @param rect       (in/out) the rect to offset from descendant to this view's coordinate system
   */
  fun offsetDescendantRect(parent: ViewGroup, descendant: View, rect: Rect) {
    IMPL!!.offsetDescendantRect(parent, descendant, rect)
  }

  /**
   * Retrieve the transformed bounding rect of an arbitrary descendant view.
   * This does not need to be a direct child.
   *
   * @param descendant descendant view to reference
   * @param out        rect to set to the bounds of the descendant view
   */
  fun getDescendantRect(parent: ViewGroup, descendant: View, out: Rect) {
    out[0, 0, descendant.width] = descendant.height
    offsetDescendantRect(parent, descendant, out)
  }

  private interface ViewGroupUtilsImpl {
    fun offsetDescendantRect(parent: ViewGroup, child: View, rect: Rect)
  }

  private class ViewGroupUtilsImplBase internal constructor() : ViewGroupUtilsImpl {
    override fun offsetDescendantRect(parent: ViewGroup, child: View, rect: Rect) {
      parent.offsetDescendantRectToMyCoords(child, rect)
      // View#offsetDescendantRectToMyCoords includes scroll offsets of the last child.
      // We need to reverse it here so that we get the rect of the view itself rather
      // than its content.
      rect.offset(child.scrollX, child.scrollY)
    }
  }

  private class ViewGroupUtilsImplHoneycomb internal constructor() : ViewGroupUtilsImpl {
    override fun offsetDescendantRect(parent: ViewGroup, child: View, rect: Rect) {
      ViewGroupUtilsHoneycomb.offsetDescendantRect(parent, child, rect)
    }
  }
}
